﻿#include "udpreceiver.h"
#include <QJsonDocument>

UdpReceiver::UdpReceiver(QObject *parent)
    : QObject{parent}
{
    receiver = new QUdpSocket(this);
}

bool UdpReceiver::setPort(int port)
{
    if(receiver->bind(port, QUdpSocket::ShareAddress)) {
        connect(receiver, &QUdpSocket::readyRead, this, &UdpReceiver::processData);
        return true;
    } else {
        return false;
    }
}

void UdpReceiver::processData()
{
    QJsonObject data;
    QByteArray datagram;
    //设置data的大小为等待处理的数据报的大小，这样才能接收到完整的数据
    datagram.resize(receiver->pendingDatagramSize());
    // 接收数据报，将其存放到datagram中
    receiver->readDatagram(datagram.data(), datagram.size());
    //处理接收数据
    QJsonDocument document = QJsonDocument::fromJson(datagram);
    data = document.object();
    //发送带json的信号
    emit receiveJson(data);
}

void UdpReceiver::breakLink()
{
    disconnect(receiver, &QUdpSocket::readyRead, this, &UdpReceiver::processData);
    receiver->close();
}
